package top.wardyan.wbaseswt.control.wtable;

import java.util.List;
import java.util.Set;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;

import com.jfinal.aop.Aop;
import com.jfinal.plugin.activerecord.IRow;

//import top.wardyan.conf.config.SQLite;
//import top.wardyan.conf.model.SysTableCol;
//import top.wardyan.conf.model.SysTableColItem;
//import top.wardyan.conf.tableColService.ISysTableColItemService;
//import top.wardyan.conf.tableColService.ISysTableColService;
import top.wardyan.wbaseswt.action.base.AbstractShell;
import top.wardyan.wbaseswt.conf.Const;
import top.wardyan.wbaseswt.conf.model.SysTableCol;
import top.wardyan.wbaseswt.conf.service.ISysTableColService;
import top.wardyan.wbaseswt.control.WButton;
import top.wardyan.wbaseswt.control.WCombo;
import top.wardyan.wbaseswt.control.WText;
import top.wardyan.wbaseswt.listener.WNumberOnlyKeyAdapter;
import top.wardyan.wbaseswt.util.KeyCode;
import top.wardyan.wbaseswt.util.Msg;
import top.wardyan.wbaseswt.util.ShellUtil;

public class WTableSettingShell extends AbstractShell<WTableSettingShell>{

	protected String classname;
	protected String tablename;
	protected WTable mainTable;
	protected IRow<? extends IRow<?>> model;
	//protected ISysTableColService tableColService = SQLite.getInstance().tablecolService;
	protected ISysTableColService tableColService = Aop.get(ISysTableColService.class);
	
	public WTableSettingShell() {
		this("top.wardyan.wbaseswt.control.wtable.WTableSettingShell", "mainTable", null);
	}
	
	public WTableSettingShell(String classname, String tablename, IRow<? extends IRow<?>> model) {
		super();
		this.classname = classname;
		this.tablename = tablename;
		this.model = model;
		this.createContent();
	}
	
	protected WText searchText;
	
	private void createContent() {
		this.setSize(800, 600);
		ShellUtil.center(this);
		this.setLayout(new FormLayout());
		
		/** 测试 **/
		this.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseDoubleClick(MouseEvent e) {
				// super.mouseDoubleClick(e);
				self.dispose();
				new WTableSettingShell().go();;
			}
		});
	
		
		searchText = new WText(this, SWT.BORDER, "", "搜索关键字");
		searchText.setTextLimit(64);
		FormData fd_searchText = new FormData();
		fd_searchText.bottom = new FormAttachment(this, 30);
		fd_searchText.left = new FormAttachment(this, 0);
		fd_searchText.right = new FormAttachment(100, -400);
		fd_searchText.top = new FormAttachment(this, 2);
		searchText.setLayoutData(fd_searchText);
		searchText.addModifyListener(new ModifyListener() {			
			@Override
			public void modifyText(ModifyEvent e) {
				mainTable.show("mainTable", searchText.getText());
			}
		});
		//  清空 恢复默认 新增 保存
		WButton btnClear = new WButton(this, SWT.PUSH, "清空", new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				clear();
			}
		});
		FormData fd_btnClear = new FormData();
		fd_btnClear.left = new FormAttachment(searchText, 2);
		fd_btnClear.top = new FormAttachment(this, 2);
		fd_btnClear.right = new FormAttachment(btnClear, 70);
		fd_btnClear.bottom = new FormAttachment(this, 30);
		btnClear.setLayoutData(fd_btnClear);

		WButton btnSetDefault = new WButton(this, SWT.PUSH, "恢复默认", new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				setDefault();
			}
		});
		FormData fd_btnSetDefault = new FormData();
		fd_btnSetDefault.left = new FormAttachment(btnClear, 2);
		fd_btnSetDefault.top = new FormAttachment(this, 2);
		fd_btnSetDefault.right = new FormAttachment(btnSetDefault, 90);
		fd_btnSetDefault.bottom = new FormAttachment(this, 30);
		btnSetDefault.setLayoutData(fd_btnSetDefault);
		WButton btnAdd = new WButton(this, SWT.PUSH, "新增", new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				add();
			}
		});
		btnAdd.setEnabled(!(self.model == null));
		FormData fd_btnAdd = new FormData();
		fd_btnAdd.left = new FormAttachment(btnSetDefault, 2);
		fd_btnAdd.top = new FormAttachment(this, 2);
		fd_btnAdd.right = new FormAttachment(btnAdd, 70);
		fd_btnAdd.bottom = new FormAttachment(this, 30);
		btnAdd.setLayoutData(fd_btnAdd);
		WButton btnAutoname = new WButton(this, SWT.PUSH, "自动命名", new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				autoname();
			}
		});
		FormData fd_btnAutoname = new FormData();
		fd_btnAutoname.bottom = new FormAttachment(this, 30);
		fd_btnAutoname.left = new FormAttachment(btnAdd, 2);
		fd_btnAutoname.right = new FormAttachment(btnAutoname, 90);
		fd_btnAutoname.top = new FormAttachment(this, 2);
		btnAutoname.setLayoutData(fd_btnAutoname);
		
		WButton btn = new WButton(this, SWT.PUSH, "保存", new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				saving();
			}
		});
		FormData fd_btn = new FormData();
		fd_btn.bottom = new FormAttachment(this, 30);
		fd_btn.left = new FormAttachment(btnAutoname, 2);
		fd_btn.right = new FormAttachment(btn, 70);
		fd_btn.top = new FormAttachment(this, 2);
		btn.setLayoutData(fd_btn);
		
		mainTable = new WTable(this, SWT.NONE, "mainTable");
		FormData fd_mainCom = new FormData();
		fd_mainCom.bottom = new FormAttachment(100, -1);
		fd_mainCom.left = new FormAttachment(this, 0);
		fd_mainCom.right = new FormAttachment(100, -1);
		fd_mainCom.top = new FormAttachment(searchText, 6);
		mainTable.setLayoutData(fd_mainCom);
		//mainCom.setLayout(new FormLayout());
		
		List<SysTableCol> cols = tableColService.list(classname, tablename);
		//mainTable.setIsAutoPack(true);
		if(cols != null) {
			mainTable.datas = cols;
			mainTable.show("mainTable", "");
		}
		mainTable.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				//组合件, CTRL+↑ 或者CTRL+ ↓, 调整顺序s
				//System.out.println(e.keyCode);
				if(mainTable.getSelectionIndex() >= 0) {
					//ISysTableColItemService itemService = SQLite.getInstance().tablecolItemService;
					TableColumn[] cols = mainTable.getColumns();
					int cindex = 0;
					if(cols != null) {
						for(TableColumn c : cols) {
							WTableColumn wc = (WTableColumn) c;
							if(wc.getXField().equals("sID")) {
								break;
							}else {
								cindex++;
							}
						}
					}
					TableItem tbitem = mainTable.getItem(mainTable.getSelectionIndex());
					String sid = tbitem.getText(cindex);
					//SysTableCol tc = tableColService.findByIDs(Integer.valueOf(sid));
					SysTableCol tc = tableColService.find(Integer.valueOf(sid));
					int tableindex = mainTable.getSelectionIndex();
					
					if(e.stateMask == SWT.CTRL && (e.keyCode == KeyCode.KEY_UP || e.keyCode == KeyCode.KEY_DOWN)) {
						SysTableCol tc2 = null;
						if(tc != null) {
							tc2 = tableColService.find(self.classname, self.tablename, tc.getSIndex() + (e.keyCode == KeyCode.KEY_UP ? -1 : 1));
						}
						if(tc != null && tc2 != null) {
							int sindex = tc.getSIndex();
							tc.setSIndex(tc2.getSIndex());
							tc2.setSIndex(sindex);
							tableColService.saveOrUpdate(tc2);
							tableColService.saveOrUpdate(tc);
							mainTable.show(self.tablename, "", tableColService.list(self.classname, self.tablename));
							mainTable.select(tableindex + (e.keyCode == KeyCode.KEY_UP ? -1 : 1));
						}
					}else if(e.keyCode == KeyCode.KEY_DELETE) {
						// 删除键
						if(tc != null) {
							boolean doit = true;
							if((tc.getXField().equals("sID") || tc.getXField().equals("mID") || tc.getXField().equals("dID"))) {
								if(Msg.confirm(self, "警告", "字段:" + tc.getXField() + " 貌似是系统字段,删掉后可能会导致严重问题,请确认!", SWT.CANCEL | SWT.OK) != SWT.OK) {
									doit = false;
								}
							}
							if(doit) {
								tableColService.delete(tc);
								var ls = tableColService.list(self.classname, self.tablename);
								mainTable.show(self.tablename, "", ls);
								mainTable.select(tableindex - 1);
							}
						}
					}
				}
			}
		});
		
		mainTable.addMouseListener(new MouseAdapter() {
			int editColumnIndex = -1;
			@Override
			public void mouseDoubleClick(MouseEvent e) {
				final Point point = new Point(e.x, e.y);
				final TableItem tableItem = mainTable.getItem(point);
				if (tableItem == null) {
					return;
				}
				for (int i = 0; i < mainTable.getColumnCount(); i++) {
					final Rectangle r = tableItem.getBounds(i);
					if (r.contains(point)) {
						editColumnIndex = i;
						final TableEditor editor = new TableEditor(mainTable);
						final Control oldEditor = editor.getEditor();
						if (oldEditor != null) {
							oldEditor.dispose();
						}
						//
						// 取出类型, 然后决定使用什么编辑器
						//
						WTableColumn wc = (WTableColumn)mainTable.getColumn(editColumnIndex);
						String field = wc.getXField();
						SysTableCol tc = tableColService.find(self.getClass().getName(), "mainTable", field);
						if(tc.getXType() == 3) {	// datetime
							// 暂不提供
						}
						// 特意不用elseif
						if(tc.getXType() == 4) {	// SELECT		// ?? TODO
//							ISysTableColItemService itemService = SQLite.getInstance().tablecolItemService;
//							List<SysTableColItem> tcitems = itemService.list(self.getClass().getName(), "mainTable", tc.getXField());
							// tcitems == null或者0行呢? 先不管
							// final Text text = new Text(mainTable, SWT.NONE);
							final WCombo select = new WCombo(mainTable, SWT.NONE);
							select.computeSize(SWT.DEFAULT, mainTable.getItemHeight());
							editor.grabHorizontal = true;
							editor.minimumHeight = select.getSize().y;
							editor.minimumWidth = select.getSize().x;
							editor.setEditor(select, tableItem, editColumnIndex);
//							SysTableColItem tcitem = itemService.find(self.getClass().getName(), "mainTable", tc.getXField(), tableItem.getText(editColumnIndex));
//							
//							if(tcitems != null) {
//								for(SysTableColItem it : tcitems) {
//									select.add(it.getStr("xName"));
//								}
//							}	
							
//							select.setText(tcitem != null ? tcitem.getStr("xName") : tableItem.getText(editColumnIndex));
//							select.forceFocus();
							
							select.addModifyListener(new ModifyListener() {
								@Override
								public void modifyText(final ModifyEvent e) {
									editor.getItem().setText(editColumnIndex, select.getText());
								}
							});
							select.addFocusListener(new FocusListener() {
								@Override
								public void focusGained(final FocusEvent e) {
									//text.selectAll();
								}
								@Override
								public void focusLost(final FocusEvent e) {
									select.setForeground(Const.COLOR_WHITE);
									select.setBackground(Const.COLOR_RED);
								}
						});
						/** **/	
							
						}else if(tc != null) {
							if(tc.getXType() == 1 || tc.getXType() == 2) {	//文本/INT
								final Text text = new Text(mainTable, SWT.NONE);
								text.computeSize(SWT.DEFAULT, mainTable.getItemHeight());
								editor.grabHorizontal = true;
								editor.minimumHeight = text.getSize().y;
								editor.minimumWidth = text.getSize().x;
								editor.setEditor(text, tableItem, editColumnIndex);
								text.setText(tableItem.getText(editColumnIndex));
								text.forceFocus();
								if(tc.getXType() == 2) {
									text.addKeyListener(new WNumberOnlyKeyAdapter());
								}
								text.addModifyListener(new ModifyListener() {
									@Override
									public void modifyText(final ModifyEvent e) {
										editor.getItem().setText(editColumnIndex, text.getText());
									}
								});
								text.addFocusListener(new FocusListener() {
									@Override
									public void focusGained(final FocusEvent e) {
										//text.selectAll();
									}
									@Override
									public void focusLost(final FocusEvent e) {
										text.setForeground(Const.COLOR_WHITE);
										text.setBackground(Const.COLOR_RED);
									}
								});
							} 
						}
					}
				}
			}
		});
		Menu mainMenu = mainTable.getMenu();
		if(mainMenu != null) {
			MenuItem mi = new MenuItem(mainMenu, SWT.PUSH);
			mi.setText("设置值替换");
			mi.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent e) {
					int index = mainTable.getSelectionIndex();
					int cindex = 0;
					int sid = 0;
					if(index >= 0) {
						TableItem item = mainTable.getItem(index);
						TableColumn[] tcs = mainTable.getColumns();
						if(tcs != null) {
							for(TableColumn t : tcs) {
								WTableColumn wc = (WTableColumn)t;
								if(wc.getXField().equals("sID")) {
									sid = Integer.valueOf(item.getText(cindex));
									break;
								}else {
									cindex ++;
								}
							}
						}
					}
					new WTableItemSettingShell(sid).go();
					self.dispose();
					new WTableSettingShell(classname, tablename, model).go();
				}
			});
		}
		
	}
	
	protected void saving() {
		TableItem[] items = mainTable.getItems();
		TableColumn[] cols = mainTable.getColumns(); 
		//List<SysTableColItem> tcitems = SQLite.getInstance().tablecolItemService.list(classname, tablename);
//		List<SysTableColItem> tcitems = SQLite.getInstance().tablecolItemService.list(self.getClass().getName(), "mainTable");
//		List<String> tcitemFields = new ArrayList<>();
//		Map<String, List<SysTableColItem>> maps = new HashMap<>();
//		
//		if(tcitems != null) {
//			for(SysTableColItem tci : tcitems) {
//				/**
//				if(!tcitemFields.contains(tci.getStr("xField"))) {
//					tcitemFields.add(tci.getStr("xField"));
//				}
//				**/
//				List<SysTableColItem> ls = maps.get(tci.getStr("xField"));
//				if(ls == null) {
//					ls = new ArrayList<>();
//				}
//				if(!ls.contains(tci)) {
//					ls.add(tci);
//				}
//				maps.put(tci.getStr("xField"),ls);
//			}
//		}
		for(TableItem item : items) {
			int i = 0;
			//String sid = item.getText(0);
			//String index = item.getText(1);
			// 没有sID,说明是新增的 // 2020-02-16 22:51:36 不行,不允许新增, 只允许用按钮新增
			int sID = 0;
			
			i = 0;
			for(TableColumn c : cols) {
				WTableColumn wc = (WTableColumn)c;
				if(wc.getXField().equals("sID")) {
					sID = Integer.valueOf(item.getText(i));
				}
				i ++;
			}
			i = 0;
			SysTableCol tc = tableColService.find(sID);
			if(tc != null) {
				for(TableColumn c : cols) {
					WTableColumn wc = (WTableColumn)c;
					//if(tcitemFields.contains(wc.getXField())) {
					// 下面这些注释掉了
//					if(wc.getXField().equals("sStatus")) {
//						tc.set(wc.getXField(), Status.getInstance(item.getText(i)).getSID());
//					}else if(maps.keySet().contains(wc.getXField())) {
//						List<SysTableColItem> ls = maps.get(wc.getXField());
//						boolean finded = false;
//						if(ls != null) {
//							for(SysTableColItem ct : ls) {
//								if(item.getText(i).equals(ct.getStr("xName"))) {
//									tc.set(wc.getXField(), ct.getInt("xValue"));
//									finded = true;
//									break;
//								}
//							}
//						}
//						if(!finded) {
//							tc.set(wc.getXField(), 0);
//						}
//					}else {
//						tc.set(wc.getXField(), item.getText(i));
//					}
					tc.set(wc.getXField(), item.getText(i));
					i ++;
				}
			}
			tableColService.update(tc);
			// SysTableCol tc = new SysTableCol();
			
		}
		Msg.show(self, "OK", "更新完成, 请重新打开窗口");
	}
	
	@Override
	protected String getTitle() {
		return "列设置";
	}
	
	public static void main(String[] args) {
		new WTableSettingShell().go();
	}

	@Override
	protected boolean isMainWindow() {
		return false;
	}
	
	
	private void clear() {
		List<SysTableCol> tcs = tableColService.list(classname, tablename);
		//ISysTableColItemService itemService = SQLite.getInstance().tablecolItemService;
		if(tcs != null) {
			for(SysTableCol t : tcs) {
				tableColService.delete(t);
			}
		}
//		List<SysTableColItem> tcitems = itemService.list(classname, tablename);
//		if(tcitems != null) {
//			for(SysTableColItem item : tcitems) {
//				itemService.delete(item);
//			}
//		}
		mainTable.show(tablename, "", tableColService.list(classname, tablename));
	}
	
	private void setDefault() {
		List<SysTableCol> tcs = tableColService.list(classname, tablename);
		if(tcs != null) {
			for(SysTableCol t : tcs) {
				tableColService.update(t.setXWidth(WTableColumn.defaultWidth(t.getXField())).setXTitle(t.getXField()));
			}
		}
		mainTable.show(tablename, "", tableColService.list(classname, tablename));
	}
	
	private void add() {
		if(model != null) {
			// String[] fields = model._getAttrNames();
			Set<String> fields = model.toMap().keySet();
			if(fields != null) {
				for(String field : fields) {
					if(tableColService.find(classname, tablename, field) == null) {
						SysTableCol tc = new SysTableCol()
								.setSIndex(tableColService.maxIndex(classname, tablename))
								.setXAlign(SWT.LEFT).setXClassName(classname).setXField(field)
								.setXFormat("").setXTitle(field).setXTableName(tablename)
								.setXWidth(WTableColumn.defaultWidth(field))
								//.setRTypeID(1)
								.setXType(1)
								.setXIsShow(true)
								// .setSStatus(2)
								;
						tableColService.save(tc);
					}
				}
			}
			mainTable.show(tablename, "", tableColService.list(classname, tablename));
		}else {
			Msg.show(self, "错误", "未提供数据格式,无法继续");
		}
	}

	private void autoname() {
		List<SysTableCol> tcs = tableColService.list(classname, tablename);
		if(tcs != null) {
			for(SysTableCol tc : tcs) {
				tableColService.update(tc.setXTitle(tableColService.getAnAutoTitle(tc.getXField())));
			}
		}
		/**
		this.dispose();
		new WTableSettingShell(classname, tablename, model).go();
		**/
		mainTable.show(tablename, "", tableColService.list(classname, tablename));
	}
}
